package com.rds.material.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.rds.common.api.material.domain.MaterialBill;
import com.rds.common.api.material.domain.RdaPart;
import com.rds.common.api.material.domain.RdaPartDynamicattributevalue;
import com.rds.common.api.material.domain.RdaPartsRel;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.Folder;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import com.rds.material.service.*;

import com.rds.material.utils.WorkspaceUtils;
import com.rds.system.service.IRdaNameCodeService;
import com.rds.system.service.IRdaPolicyService;
import com.rds.system.service.IRdaStateService;
import com.rds.system.service.IRdaTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/pms/material")
public class RdaMaterialController extends BaseController {
    @Autowired
    private IRdaPartService rdaMaterialService;
    @Autowired
    private IRdaPartsRelService rdaPartsRelService;

    @Autowired
    private IRdaPartDynamicattributeService rdaPartDynamicattributeService;

    @Autowired
    private IRdaPartDynamicattributevalueService rdaPartDynamicattributevalueService;

    @Autowired
    private IRdaTypeService rdaTypeService;

    @Autowired
    private IRdaPolicyService rdaPolicyService;

    @Autowired
    private IRdaStateService rdaStateService;

    @Autowired
    private IMaterialBillService materialBillService;


    @Autowired
    private IMaterialBillService iMaterialBillService;


    @Autowired
    private IRdaNameCodeService rdaNameCodeService;

    /**
     * 物料分类查询
     */
    @PreAuthorize("@ss.hasPermi('pms:material:query')")
    @GetMapping(value = "/{id}")
    public JSONObject getInfo(@PathVariable("id") Long id)
    {
        return rdaMaterialService.getInfo(id);
    }

    /**
     * 零件列表查询
     */
    @PreAuthorize("@ss.hasPermi('pms:material:query')")
    @GetMapping(value = "/list/{id}")
    public JSONObject getListInfo(@PathVariable("id") Long id)
    {
        return rdaMaterialService.getInfos(id);
    }

    @PreAuthorize("@ss.hasPermi('pms:material:query')")
    @GetMapping(value = "/rel/{id}")
    public JSONObject getrelInfo(@PathVariable("id") Long id)
    {
        return rdaMaterialService.getrelInfo(id);
    }

    /**
     * 物料分类查询
     */
    @GetMapping("/list")
    public TableDataInfo list(RdaPart rdaPart){
        startPage();
        if(rdaPart.getParentid()==null){
            rdaPart.setParentid(0L);
        }
        return getDataTable(rdaMaterialService.selectRdaPartList(rdaPart));
    }

    /**
     * 物料分类查询--区分角色
     */
    @GetMapping("/listAuth")
    public TableDataInfo listAuth(RdaPart rdaPart){
        startPage();
        if(rdaPart.getParentid()==null){
            rdaPart.setParentid(0L);
        }
        Long userId = SecurityUtils.getUserId();
        System.out.println("userId=="+userId);
        rdaPart.setOwnerid(userId);
        return getDataTable(rdaMaterialService.selectRdaPartList(rdaPart));
    }

    /**
     * 零件列表
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/listMyPart")
    public TableDataInfo listMyPart(MaterialBill materialBill)
    {
        startPage();
//        List<MaterialBill> materialBillList = materialBillService.selectMaterialBillList(materialBill);

        List<MaterialBill> materialBillList = materialBillService.selectMaterialBillListLJRel(materialBill);
        return getDataTable(materialBillList);
    }


    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @DeleteMapping("/delMyPart/{ids}")
    public AjaxResult delMyPart(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            materialBillService.deleteMaterialBillById(id);
        }
        return AjaxResult.success();
    }


    /**
     * 物料分类查询
     */
    @PreAuthorize("@ss.hasPermi('pms:material:materialList')")
    @GetMapping("/materialList")
    public TableDataInfo materialList(RdaPart rdaPart){
        List<RdaPart> rdaPart3 =new ArrayList<>();
        List<RdaPart>  materialTree=rdaMaterialService.selectRdaPartTreeList(rdaPart);
        materialTree.forEach((RdaPart rdaPart2)->{
            if(!rdaPart2.getParentid().equals(0L)){
                rdaPart2.setProjectid(null);
                rdaPart3.add(rdaPart2);
            }
        });
        return getDataTable(rdaPart3);
    }

    /**
     * 物料分类查询
     */
    @PreAuthorize("@ss.hasPermi('pms:material:partsList')")
    @GetMapping("/partsList")
    public JSONObject partsList(ServletRequest request){
        return iMaterialBillService.partsList(request);
    }

    /**
     * 物料分类子库查询
     */
    @PreAuthorize("@ss.hasPermi('pms:material:partsSubLevelList')")
    @GetMapping("/partsSubLevelList")
    public JSONObject partsSubLevelList(ServletRequest request){
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("Classification","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("Part Family");
        JSONObject jsonobj = new JSONObject();
        //通过任务id获取当前节点id
        ArrayList<String> jsonList=new ArrayList<String>();
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String projectid=httpRequest.getParameter("projectid");
        RdaPart part=new RdaPart();
        part.setParentid(Long.parseLong(projectid));
        part.setTypeid(typeid);
        List<RdaPart> rdaPartList=rdaMaterialService.selectRdaPartList(part);
        rdaPartList.forEach((RdaPart rdaPart)->{
            StringBuilder json=new StringBuilder();
            String stringJSON = JSON.toJSONString(rdaPart);
            json.append(stringJSON);
            RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
            rdaPartDynamicattributevalue.setObjectid(rdaPart.getId());
            List<RdaPartDynamicattributevalue> rdaPartDynamicattributevalueList=rdaPartDynamicattributevalueService.selectRdaPartDynamicattributevalueList(rdaPartDynamicattributevalue);
            String attribute = "";
            for(RdaPartDynamicattributevalue partDynamicattributevalue:rdaPartDynamicattributevalueList){
                attribute += ",\""+partDynamicattributevalue.getAttributeName()+"\":\""+partDynamicattributevalue.getAttributeValue()+"\"";//字符串两边含有双引号
            }
            if(attribute!=null && attribute.length()>0){

                json.insert(json.length()-1,attribute);
            }
            jsonList.add(json.toString());
        });
//        JSONArray jarr = JSONArray.fromObject(jsonList);
        String jarr = JSON.toJSONString(jsonList);
        JSONArray jsonArray = JSONArray.parseArray(jarr);
        List<Object> list = JSON.parseArray(jsonArray.toJSONString(), Object.class);
        List<JSONObject> result = new ArrayList<>();
        for (Object obj : list) {
            JSONObject jsonObject = JSON.parseObject(obj.toString());
            result.add(jsonObject);
        }
        jsonobj.put("rows",result);
        jsonobj.put("total",rdaPartList.size());
        return jsonobj;
    }


    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('pms:material:query')")
    @PutMapping
    public AjaxResult updateMaterialAddRel(@RequestBody Map<String,Object> map)
    {
        return toAjax(rdaPartsRelService.updateMaterialAddRel(map));
    }


    /**
     * 物料分类新增
     */
    @PreAuthorize("@ss.hasPermi('pms:material:add')")
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody RdaPart rdaPart){
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("Libraries","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("Part Library");
        Long dPolicyid=(Long)dmap.get("Policyid");
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        Long dstateid=(Long)dstateMap.get("Active");
        Long id=SnowFlakeUtils.nextId();
        rdaPart.setId(id);
        rdaPart.setParentid(0L);
        rdaPart.setProjectid(id);
        rdaPart.setCreateTime(DateUtils.getNowDate());
        rdaPart.setModifyTime(DateUtils.getNowDate());
        rdaPart.setTypeid(typeid);
        rdaPart.setPolicyid(dPolicyid);
        rdaPart.setStateid(dstateid);
        return toAjax(rdaMaterialService.insertRdaPart(rdaPart));
    }

    /**
     * 删除物料分类
     */
    @PreAuthorize("@ss.hasPermi('pms:material:remove')")
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        rdaPartDynamicattributevalueService.deleteRdaPartDynamicattributevalueByObjectId(ids);
        //删除库
        int row=rdaMaterialService.deleteRdaPartByIds(ids);
        //删除库下的零件
        int i = iMaterialBillService.deleteMaterialBillByMid(ids[0]);

        return toAjax(row);
    }

    /**
     * 删除零件
     */
    @PreAuthorize("@ss.hasPermi('pms:material:remove')")
    @DeleteMapping("/bill/{ids}")
    @Transactional
    public AjaxResult removeBill(@PathVariable Long[] ids)
    {
        int row = rdaMaterialService.deleteMaterialBillTrees(ids);
        return toAjax(row);
    }

    /**
     * 加载列表树
     */
    @GetMapping("/getMaterialTree")
    public AjaxResult getMaterialTree(RdaPart rdaPart){
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("Classification","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("Part Family");
        rdaPart.setTypeid(typeid);
        List<RdaPart>  materialTree=rdaMaterialService.selectRdaPartTreeList(rdaPart);
        List<Folder> folders=new ArrayList<Folder>();
        materialTree.forEach((RdaPart rdaPart2)->{
            if(!rdaPart2.getParentid().equals(0L)){
                Folder folder=new Folder();
                folder.setId(rdaPart2.getId());
                MaterialBill materialBill = new MaterialBill();
                materialBill.setMaterialid(rdaPart2.getId());
                materialBill.setParentid(rdaPart2.getId());
                materialBill.setStatus(1);
                RdaPartsRel rdaPartsRel = new RdaPartsRel();
                rdaPartsRel.setParentId(rdaPart2.getId());
                int size = rdaPartsRelService.selectRdaPartsRelList(rdaPartsRel).size();
                folder.setSum(Long.parseLong(String.valueOf(size)));
                folder.setParentid(rdaPart2.getParentid());
                folder.setProjectid(rdaPart2.getProjectid());
                folder.setFolderName(rdaPart2.getName());
                folder.setDescription(rdaPart2.getDescription());
                folder.setStatus(rdaPart2.getStatus());
                folder.setOwnerid(rdaPart2.getOwnerid());
                folders.add(folder);
            }
        });
        //统计根节点数量
        Long totalSum = folders.stream()
                .mapToLong(Folder::getSum)
                .sum();
        //对每个系列下的零件进行统计汇总
        // 使用 for 循环进行倒序遍历
        for (int i = folders.size() - 1; i >= 0; i--) {
            Folder folder = folders.get(i);
            //如果有父级就把数量与父级相加
            for (Folder folder1 : folders) {
                if (folder1.getId().equals(folder.getParentid())){
                    folder1.setSum(folder1.getSum()+folder.getSum());
                }
            }
            folder.setFolderName(folder.getFolderName()+"("+folder.getSum()+")");
        }

        return AjaxResult.success(folders).put("total",totalSum);
    }

    /**
     * 物料分类新增
     */
    @PreAuthorize("@ss.hasPermi('pms:material:partsAdd')")
    @PostMapping("/partsAdd")
    @Transactional
    public AjaxResult partsAdd(@RequestBody RdaPart rdaPart){
        Long id=SnowFlakeUtils.nextId();
        rdaPart.setId(id);
        rdaPart.setParentid(rdaPart.getProjectid());
        return toAjax(rdaMaterialService.insertRdaPart(rdaPart));
    }

    /**
     * 零件新增
     */
    @PreAuthorize("@ss.hasPermi('pms:material:materialAdd')")
    @PostMapping("/materialAdd")
    @Transactional
    public AjaxResult materialAdd(@RequestBody Map<String,Object> map){
        int number = materialBillService.materialAdd(map);
        return toAjax(number);
    }

    /**
     * 物料分类子库新增
     */
    @PreAuthorize("@ss.hasPermi('pms:material:materialSubLevelAdd')")
    @PostMapping("/materialSubLevelAdd")
    @Transactional
    public AjaxResult materialSubLevelAdd(@RequestBody RdaPart rdaPart,Long pmsid){
        Long id=SnowFlakeUtils.nextId();
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("Classification","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("Part Family");
        Long dPolicyid=(Long)dmap.get("Policyid");
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        Long dstateid=(Long)dstateMap.get("Active");
        rdaPart.setId(id);
        rdaPart.setTypeid(typeid);
        rdaPart.setPolicyid(dPolicyid);
        rdaPart.setStateid(dstateid);
        if (rdaPart.getParentid()==0){
            rdaPart.setParentid(rdaPart.getProjectid());
        }else {
            rdaPart.setParentid(rdaPart.getParentid());
        }
        rdaPart.setProjectid(rdaPart.getProjectid());
        return toAjax(rdaMaterialService.insertRdaPart(rdaPart));
    }

    /**
     * 物料分类子库新增
     */
    @PreAuthorize("@ss.hasPermi('pms:material:materialSubordinateAdd')")
    @PostMapping("/materialSubordinateAdd")
    @Transactional
    public AjaxResult materialSubordinateAdd(@RequestBody RdaPart rdaPart){
        Long id=SnowFlakeUtils.nextId();
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("partSeries","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("partSeries");
        Long dPolicyid=(Long)dmap.get("Policyid");
        Map<String,Object> dstateMap=(Map)dmap.get("Stateid");
        Long dstateid=(Long)dstateMap.get("Active");

        rdaPart.setId(id);
        rdaPart.setTypeid(typeid);
        rdaPart.setPolicyid(dPolicyid);
        rdaPart.setStateid(dstateid);
        return toAjax(rdaMaterialService.insertRdaPart(rdaPart));
    }

    /**
     * 修改零部件子库
     */
    @PreAuthorize("@ss.hasPermi('pms:material:materialSubLevelEdit')")
    @PutMapping("/materialSubLevelEdit")
    @Transactional
    public AjaxResult materialSubLevelEdit(@RequestBody RdaPart rdaPart){
        return toAjax(rdaMaterialService.updateRdaPart(rdaPart));
    }

    /**
     * 物料分类子库查询
     */
    @PreAuthorize("@ss.hasPermi('pms:material:materialSubLevelEdit')")
    @GetMapping(value = "/materialSubLevelEdit/{id}")
    public AjaxResult materialSubLevelGetInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(rdaMaterialService.selectRdaPartByid(id));

    }
}
